import os
from ivic.core import Config, project_path
from ivic.core import Logging
from ivic.vprocess.Server import VProcessServer
from ivic.vprocess.Config import *
from ivic.vprocess.VprocessMonitor import *
from ivic.vprocess.ServerMonitor import *


logger = Logging.get_logger('ivic.vprocess.Plugin')

__obj = None
__VprocessTracker = None
__VprocessReporter = None
__VprocessServerMonitor = None

def init(daemon_config):
    config = Config.load(project_path('/etc/ivic/vprocess.yaml'))

    #create and modify the configuration of curlget download path
    try:
        if not os.path.exists("/var/tmp/ivic/curlget/"):
            os.makedirs("/var/tmp/ivic/curlget/", 0777)
        curl_conf = open("/var/tmp/ivic/curlget/urlprefix.config", "w")
        curl_conf.write(config['transfer']['urlprefix'])
        curl_conf.close()
    except:
        pass
    
    Logging.get_logger('ivic.vprocess.Plugin', filename=config['log_file'])
    Logging.get_logger('ivic.vprocess.Vprocess', filename=config['log_file'])
    Logging.get_logger('ivic.vprocess.UnionMount', filename=config['log_file'])
    Logging.get_logger('ivic.vprocess.Server', filename=config['log_file'])
    Logging.get_logger('ivic.vprocess.VprocessMonitor', filename=config['log_file'])
    Logging.get_logger('ivic.vprocess.ServerMonitor', filename=config['log_file'])
    Logging.get_logger('ivic.vprocess.XmlParse', filename=config['log_file'])
    Logging.get_logger('ivic.vprocess.HostConfig', filename=config['log_file'])
    
    logger.debug('initializing %s' % __name__)
    global __obj
    if __obj:
        logger.error('[Server]reinitialized is not supported')
        return

    __obj = VProcessServer()
    
    global __VprocessTracker
    if __VprocessTracker:
        logger.error('[Tracker]reinitialized is not supported')
        return
    
    __VprocessTracker = VprocessTracker(__obj)
    __VprocessTracker.start()
    
    portal = vprocess_config.portal_url
    if portal == None:
        raise Exception("no portal set. can not report information")
    
    if portal[-1] != '/':
        portal = portal + "/"
    
#*****************************************************************************    
    global __VprocessServerMonitor
    if __VprocessServerMonitor:
        logger.error('[Tracker]reinitialized is not supported')
        return
    try:
#        server_url = None
#        try:
#            server_url = config['monitor']['url']
#            if server_url != None:
#                server_url = server_url + '/vsaasmonitor/update_status'
#        except Exception, e:
#            logger.error('%s' % e)
        server_url = portal + "vsaasmonitor/update_status" 
        __VprocessServerMonitor = ServerMonitor(server_url,'linux-vprocess')
        __VprocessServerMonitor.start()
        __obj.setServerMonitor(__VprocessServerMonitor)
    except Exception, e:
        logger.error('%s' % e)
#*****************************************************************************

    global __VprocessReporter
    if __VprocessReporter:
        logger.error('[Reporter]reinitialized is not supported')
        return
    
    try:
        url = portal + "vprocess/"
    except Exception, e:
        url = None
        
    __VprocessReporter = VprocessReporter.Instance(url)
    if not __VprocessReporter.isAlive():
        __VprocessReporter.start()
    
def fini():
    global __obj 
    del __obj
    
    try:
        global __VprocessTracker
        __VprocessTracker.stop()
        __VprocessTracker.join()
        del __VprocessTracker
    except:
        pass
    
    try:
        global __VprocessReporter
        __VprocessReporter.stop()
        __VprocessReporter.join()
        del __VprocessReporter
    except:
        pass
    
def soap_mods():
    global __obj
    return {'/vprocess': __obj}

def wsgi_mods():
    return {}
